package com.chujian.framework.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import com.chujian.framework.core.tsdata.TsDataConst;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class WebUs {

    /**
     * 获取请求的Header
     *
     * @param header header
     * @return header
     */
    public static String getRequestHeader(String header) {
        return getRequest().getHeader(header);
    }

    /**
     * 获取请求描述
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
    }

    /**
     * 准备查询参数
     *
     * @param data   数据对象
     * @param params 所有参数
     */
    @SuppressWarnings("unchecked")
    public static void prepareQueryData(Object data, Map<String, String> params) {
        // ## 处理 q 的参数解析
        Field qField = ReflectUtil.getField(data.getClass(), TsDataConst.COMMON_QUERY_FIELD);
        if (null != qField) {
            List<String> extQueries = params.keySet()
                    .stream()
                    .filter(e -> e.contains("__"))
                    .collect(Collectors.toList());
            if (CollUtil.isNotEmpty(extQueries)) {
                Map<String, String> q = (Map<String, String>) ReflectUtil.getFieldValue(data, qField);
                for (String query : extQueries) {
                    q.put(query, params.get(query));
                }
            }
        }
    }

}
